<template>
  <div class="min-h-screen bg-gray-50 p-6">
    <!-- 页面头部 -->
    <div class="mb-6">
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-2xl font-bold text-gray-900">宿舍管理</h1>
          <p class="mt-1 text-sm text-gray-600">管理楼宇信息、宿舍分配、入住登记等宿舍相关事务</p>
        </div>
        <div class="flex items-center gap-3">
          <button
            @click="showBuildingModal = true"
            class="inline-flex items-center px-4 py-2 bg-green-600 text-white text-sm font-medium rounded-lg hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 transition-colors"
          >
            <BuildingOfficeIcon class="w-4 h-4 mr-2" />
            添加楼宇
          </button>
          <button
            @click="showAddModal = true"
            class="inline-flex items-center px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors"
          >
            <PlusIcon class="w-4 h-4 mr-2" />
            添加宿舍
          </button>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <BuildingOfficeIcon class="h-8 w-8 text-blue-600" />
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">总楼宇数</p>
            <p class="text-2xl font-semibold text-gray-900">{{ buildings.length }}</p>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <HomeIcon class="h-8 w-8 text-green-600" />
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">总宿舍数</p>
            <p class="text-2xl font-semibold text-gray-900">{{ dormitories.length }}</p>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <UsersIcon class="h-8 w-8 text-yellow-600" />
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">已入住</p>
            <p class="text-2xl font-semibold text-gray-900">{{ occupiedCount }}</p>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <CheckCircleIcon class="h-8 w-8 text-purple-600" />
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">空余床位</p>
            <p class="text-2xl font-semibold text-gray-900">{{ availableBeds }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-6">
      <div class="grid grid-cols-1 md:grid-cols-6 gap-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">宿舍号</label>
          <input
            v-model="searchForm.roomNumber"
            type="text"
            placeholder="请输入宿舍号"
            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
          />
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">所属楼宇</label>
          <Listbox v-model="searchForm.building">
            <div class="relative">
              <ListboxButton class="relative w-full cursor-default rounded-lg bg-white py-2 pl-3 pr-10 text-left border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                <span class="block truncate">{{ searchForm.building || '请选择楼宇' }}</span>
                <span class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2">
                  <ChevronUpDownIcon class="h-5 w-5 text-gray-400" aria-hidden="true" />
                </span>
              </ListboxButton>
              <transition
                leave-active-class="transition duration-100 ease-in"
                leave-from-class="opacity-100"
                leave-to-class="opacity-0"
              >
                <ListboxOptions class="absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-md bg-white py-1 text-base shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none">
                  <ListboxOption value="" class="relative cursor-default select-none py-2 pl-10 pr-4 text-gray-900 hover:bg-blue-100">
                    <span class="block truncate font-normal">全部楼宇</span>
                  </ListboxOption>
                  <ListboxOption
                    v-for="building in buildings"
                    :key="building.id"
                    :value="building.name"
                    v-slot="{ active, selected }"
                    class="relative cursor-default select-none py-2 pl-10 pr-4"
                    :class="active ? 'bg-blue-100 text-blue-900' : 'text-gray-900'"
                  >
                    <span class="block truncate" :class="selected ? 'font-medium' : 'font-normal'">
                      {{ building.name }}
                    </span>
                    <span v-if="selected" class="absolute inset-y-0 left-0 flex items-center pl-3 text-blue-600">
                      <CheckIcon class="h-5 w-5" aria-hidden="true" />
                    </span>
                  </ListboxOption>
                </ListboxOptions>
              </transition>
            </div>
          </Listbox>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">楼层</label>
          <select
            v-model="searchForm.floor"
            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
          >
            <option value="">全部楼层</option>
            <option v-for="i in 20" :key="i" :value="i">{{ i }}楼</option>
          </select>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">宿舍类型</label>
          <select
            v-model="searchForm.type"
            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
          >
            <option value="">全部类型</option>
            <option value="4人间">4人间</option>
            <option value="6人间">6人间</option>
            <option value="8人间">8人间</option>
          </select>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">入住状态</label>
          <select
            v-model="searchForm.status"
            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
          >
            <option value="">全部状态</option>
            <option value="空闲">空闲</option>
            <option value="部分入住">部分入住</option>
            <option value="已满">已满</option>
            <option value="维修中">维修中</option>
          </select>
        </div>
        <div class="flex items-end gap-2">
          <button
            @click="handleSearch"
            class="flex-1 px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors"
          >
            <MagnifyingGlassIcon class="w-4 h-4 mr-2 inline" />
            搜索
          </button>
          <button
            @click="handleReset"
            class="px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-lg hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors"
          >
            重置
          </button>
        </div>
      </div>
    </div>

    <!-- 宿舍列表 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200">
      <div class="px-6 py-4 border-b border-gray-200">
        <div class="flex items-center justify-between">
          <h2 class="text-lg font-medium text-gray-900">宿舍列表</h2>
          <div class="flex items-center gap-4">
            <span class="text-sm text-gray-500">共 {{ filteredDormitories.length }} 间宿舍</span>
            <div class="flex items-center gap-2">
              <button
                @click="handleBatchAssign"
                :disabled="selectedDormitories.length === 0"
                class="px-3 py-1.5 text-sm font-medium text-purple-600 bg-purple-50 rounded-lg hover:bg-purple-100 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                <UserPlusIcon class="w-4 h-4 mr-1 inline" />
                批量分配
              </button>
              <button
                @click="handleBatchDelete"
                :disabled="selectedDormitories.length === 0"
                class="px-3 py-1.5 text-sm font-medium text-red-600 bg-red-50 rounded-lg hover:bg-red-100 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                <TrashIcon class="w-4 h-4 mr-1 inline" />
                批量删除
              </button>
              <button
                @click="handleExport"
                class="px-3 py-1.5 text-sm font-medium text-green-600 bg-green-50 rounded-lg hover:bg-green-100 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 transition-colors"
              >
                <ArrowDownTrayIcon class="w-4 h-4 mr-1 inline" />
                导出
              </button>
            </div>
          </div>
        </div>
      </div>

      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-6 py-3 text-left">
                <input
                  type="checkbox"
                  :checked="selectedDormitories.length === filteredDormitories.length && filteredDormitories.length > 0"
                  @change="handleSelectAll"
                  class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                />
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">宿舍号</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">所属楼宇</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">楼层</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">类型</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">入住情况</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">设施</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="dormitory in paginatedDormitories" :key="dormitory.id" class="hover:bg-gray-50">
              <td class="px-6 py-4">
                <input
                  type="checkbox"
                  :value="dormitory.id"
                  v-model="selectedDormitories"
                  class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                />
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="flex items-center">
                  <div>
                    <div class="text-sm font-medium text-gray-900">{{ dormitory.roomNumber }}</div>
                    <div class="text-sm text-gray-500">{{ dormitory.building }}</div>
                  </div>
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ dormitory.building }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ dormitory.floor }}楼</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ dormitory.type }}</td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="flex items-center">
                  <div class="flex-shrink-0 w-10 h-2 bg-gray-200 rounded-full overflow-hidden">
                    <div 
                      class="h-full bg-blue-600 transition-all duration-300"
                      :style="{ width: `${(dormitory.occupiedBeds / dormitory.totalBeds) * 100}%` }"
                    ></div>
                  </div>
                  <span class="ml-2 text-sm text-gray-900">
                    {{ dormitory.occupiedBeds }}/{{ dormitory.totalBeds }}
                  </span>
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span
                  :class="{
                    'bg-green-100 text-green-800': dormitory.status === '空闲',
                    'bg-yellow-100 text-yellow-800': dormitory.status === '部分入住',
                    'bg-red-100 text-red-800': dormitory.status === '已满',
                    'bg-gray-100 text-gray-800': dormitory.status === '维修中'
                  }"
                  class="inline-flex px-2 py-1 text-xs font-semibold rounded-full"
                >
                  {{ dormitory.status }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="flex items-center gap-1">
                  <span v-if="dormitory.facilities.includes('空调')" class="text-blue-500" title="空调">
                    <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                      <path d="M10 2L3 7v11a2 2 0 002 2h10a2 2 0 002-2V7l-7-5zM8 15v-3h4v3H8z"/>
                    </svg>
                  </span>
                  <span v-if="dormitory.facilities.includes('独卫')" class="text-green-500" title="独卫">
                    <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                      <path d="M3 4a1 1 0 011-1h12a1 1 0 011 1v2a1 1 0 01-1 1H4a1 1 0 01-1-1V4zM3 10a1 1 0 011-1h6a1 1 0 011 1v6a1 1 0 01-1 1H4a1 1 0 01-1-1v-6zM14 9a1 1 0 00-1 1v6a1 1 0 001 1h2a1 1 0 001-1v-6a1 1 0 00-1-1h-2z"/>
                    </svg>
                  </span>
                  <span v-if="dormitory.facilities.includes('阳台')" class="text-yellow-500" title="阳台">
                    <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                      <path d="M10 2L3 7v11a2 2 0 002 2h10a2 2 0 002-2V7l-7-5z"/>
                    </svg>
                  </span>
                  <span v-if="dormitory.facilities.includes('热水器')" class="text-red-500" title="热水器">
                    <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                      <path d="M10 2a6 6 0 00-6 6v3.586l-.707.707A1 1 0 004 14h12a1 1 0 00.707-1.707L16 11.586V8a6 6 0 00-6-6zM10 18a3 3 0 01-3-3h6a3 3 0 01-3 3z"/>
                    </svg>
                  </span>
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <div class="flex items-center gap-2">
                  <button
                    @click="handleManageResidents(dormitory)"
                    class="text-purple-600 hover:text-purple-900 transition-colors"
                    title="管理住宿"
                  >
                    <UsersIcon class="w-4 h-4" />
                  </button>
                  <button
                    @click="handleEdit(dormitory)"
                    class="text-blue-600 hover:text-blue-900 transition-colors"
                    title="编辑"
                  >
                    <PencilIcon class="w-4 h-4" />
                  </button>
                  <button
                    @click="handleView(dormitory)"
                    class="text-green-600 hover:text-green-900 transition-colors"
                    title="查看详情"
                  >
                    <EyeIcon class="w-4 h-4" />
                  </button>
                  <button
                    @click="handleDelete(dormitory)"
                    class="text-red-600 hover:text-red-900 transition-colors"
                    title="删除"
                  >
                    <TrashIcon class="w-4 h-4" />
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 分页 -->
      <div class="px-6 py-4 border-t border-gray-200">
        <div class="flex items-center justify-between">
          <div class="text-sm text-gray-500">
            显示第 {{ (currentPage - 1) * pageSize + 1 }} - {{ Math.min(currentPage * pageSize, filteredDormitories.length) }} 条，共 {{ filteredDormitories.length }} 条
          </div>
          <div class="flex items-center gap-2">
            <button
              @click="currentPage--"
              :disabled="currentPage === 1"
              class="px-3 py-1 text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              上一页
            </button>
            <span class="px-3 py-1 text-sm font-medium text-gray-700">
              {{ currentPage }} / {{ totalPages }}
            </span>
            <button
              @click="currentPage++"
              :disabled="currentPage === totalPages"
              class="px-3 py-1 text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              下一页
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑宿舍弹窗 -->
    <Dialog :open="showAddModal || showEditModal" @close="closeModal" class="relative z-50">
      <div class="fixed inset-0 bg-black/30" aria-hidden="true" />
      <div class="fixed inset-0 flex items-center justify-center p-4">
        <DialogPanel class="w-full max-w-2xl rounded-lg bg-white p-6 shadow-xl">
          <DialogTitle class="text-lg font-medium text-gray-900 mb-4">
            {{ showAddModal ? '添加宿舍' : '编辑宿舍' }}
          </DialogTitle>
          
          <form @submit.prevent="handleSubmit" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">宿舍号 *</label>
                <input
                  v-model="formData.roomNumber"
                  type="text"
                  required
                  placeholder="请输入宿舍号"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                  :class="{ 'border-red-300': errors.roomNumber }"
                />
                <p v-if="errors.roomNumber" class="mt-1 text-sm text-red-600">{{ errors.roomNumber }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">所属楼宇 *</label>
                <Listbox v-model="formData.building">
                  <div class="relative">
                    <ListboxButton class="relative w-full cursor-default rounded-lg bg-white py-2 pl-3 pr-10 text-left border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                      <span class="block truncate">{{ formData.building || '请选择楼宇' }}</span>
                      <span class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2">
                        <ChevronUpDownIcon class="h-5 w-5 text-gray-400" aria-hidden="true" />
                      </span>
                    </ListboxButton>
                    <transition
                      leave-active-class="transition duration-100 ease-in"
                      leave-from-class="opacity-100"
                      leave-to-class="opacity-0"
                    >
                      <ListboxOptions class="absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-md bg-white py-1 text-base shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none">
                        <ListboxOption
                          v-for="building in buildings"
                          :key="building.id"
                          :value="building.name"
                          v-slot="{ active, selected }"
                          class="relative cursor-default select-none py-2 pl-10 pr-4"
                          :class="active ? 'bg-blue-100 text-blue-900' : 'text-gray-900'"
                        >
                          <span class="block truncate" :class="selected ? 'font-medium' : 'font-normal'">
                            {{ building.name }}
                          </span>
                          <span v-if="selected" class="absolute inset-y-0 left-0 flex items-center pl-3 text-blue-600">
                            <CheckIcon class="h-5 w-5" aria-hidden="true" />
                          </span>
                        </ListboxOption>
                      </ListboxOptions>
                    </transition>
                  </div>
                </Listbox>
                <p v-if="errors.building" class="mt-1 text-sm text-red-600">{{ errors.building }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">楼层 *</label>
                <select
                  v-model.number="formData.floor"
                  required
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                >
                  <option value="">请选择楼层</option>
                  <option v-for="i in 20" :key="i" :value="i">{{ i }}楼</option>
                </select>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">宿舍类型 *</label>
                <select
                  v-model="formData.type"
                  required
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                >
                  <option value="">请选择类型</option>
                  <option value="4人间">4人间</option>
                  <option value="6人间">6人间</option>
                  <option value="8人间">8人间</option>
                </select>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">床位数 *</label>
                <input
                  v-model.number="formData.totalBeds"
                  type="number"
                  required
                  min="1"
                  max="8"
                  placeholder="请输入床位数"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                />
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">状态</label>
                <select
                  v-model="formData.status"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                >
                  <option value="空闲">空闲</option>
                  <option value="部分入住">部分入住</option>
                  <option value="已满">已满</option>
                  <option value="维修中">维修中</option>
                </select>
              </div>
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">宿舍设施</label>
              <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
                <label class="flex items-center">
                  <input
                    type="checkbox"
                    value="空调"
                    v-model="formData.facilities"
                    class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                  />
                  <span class="ml-2 text-sm text-gray-700">空调</span>
                </label>
                <label class="flex items-center">
                  <input
                    type="checkbox"
                    value="独卫"
                    v-model="formData.facilities"
                    class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                  />
                  <span class="ml-2 text-sm text-gray-700">独卫</span>
                </label>
                <label class="flex items-center">
                  <input
                    type="checkbox"
                    value="阳台"
                    v-model="formData.facilities"
                    class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                  />
                  <span class="ml-2 text-sm text-gray-700">阳台</span>
                </label>
                <label class="flex items-center">
                  <input
                    type="checkbox"
                    value="热水器"
                    v-model="formData.facilities"
                    class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                  />
                  <span class="ml-2 text-sm text-gray-700">热水器</span>
                </label>
              </div>
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">备注</label>
              <textarea
                v-model="formData.remarks"
                rows="3"
                placeholder="请输入备注信息"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
              ></textarea>
            </div>
            
            <div class="flex justify-end gap-3 pt-4">
              <button
                type="button"
                @click="closeModal"
                class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors"
              >
                取消
              </button>
              <button
                type="submit"
                :disabled="loading"
                class="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                {{ loading ? '保存中...' : (showAddModal ? '添加' : '保存') }}
              </button>
            </div>
          </form>
        </DialogPanel>
      </div>
    </Dialog>

    <!-- 添加楼宇弹窗 -->
    <Dialog :open="showBuildingModal" @close="showBuildingModal = false" class="relative z-50">
      <div class="fixed inset-0 bg-black/30" aria-hidden="true" />
      <div class="fixed inset-0 flex items-center justify-center p-4">
        <DialogPanel class="w-full max-w-lg rounded-lg bg-white p-6 shadow-xl">
          <DialogTitle class="text-lg font-medium text-gray-900 mb-4">
            添加楼宇
          </DialogTitle>
          
          <form @submit.prevent="handleAddBuilding" class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">楼宇名称 *</label>
              <input
                v-model="buildingForm.name"
                type="text"
                required
                placeholder="请输入楼宇名称"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
              />
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">楼宇类型</label>
              <select
                v-model="buildingForm.type"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
              >
                <option value="男生宿舍">男生宿舍</option>
                <option value="女生宿舍">女生宿舍</option>
                <option value="混合宿舍">混合宿舍</option>
              </select>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">总楼层数 *</label>
              <input
                v-model.number="buildingForm.floors"
                type="number"
                required
                min="1"
                max="30"
                placeholder="请输入总楼层数"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
              />
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">地址</label>
              <input
                v-model="buildingForm.address"
                type="text"
                placeholder="请输入楼宇地址"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
              />
            </div>
            
            <div class="flex justify-end gap-3 pt-4">
              <button
                type="button"
                @click="showBuildingModal = false"
                class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors"
              >
                取消
              </button>
              <button
                type="submit"
                class="px-4 py-2 text-sm font-medium text-white bg-green-600 rounded-lg hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 transition-colors"
              >
                添加
              </button>
            </div>
          </form>
        </DialogPanel>
      </div>
    </Dialog>

    <!-- 查看宿舍详情弹窗 -->
    <Dialog :open="showViewModal" @close="showViewModal = false" class="relative z-50">
      <div class="fixed inset-0 bg-black/30" aria-hidden="true" />
      <div class="fixed inset-0 flex items-center justify-center p-4">
        <DialogPanel class="w-full max-w-2xl rounded-lg bg-white p-6 shadow-xl">
          <DialogTitle class="text-lg font-medium text-gray-900 mb-4">
            宿舍详情
          </DialogTitle>
          
          <div v-if="viewData" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">宿舍号</label>
                <p class="text-sm text-gray-900">{{ viewData.roomNumber }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">所属楼宇</label>
                <p class="text-sm text-gray-900">{{ viewData.building }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">楼层</label>
                <p class="text-sm text-gray-900">{{ viewData.floor }}楼</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">宿舍类型</label>
                <p class="text-sm text-gray-900">{{ viewData.type }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">床位情况</label>
                <p class="text-sm text-gray-900">{{ viewData.occupiedBeds }}/{{ viewData.totalBeds }} 已入住</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">状态</label>
                <span
                  :class="{
                    'bg-green-100 text-green-800': viewData.status === '空闲',
                    'bg-yellow-100 text-yellow-800': viewData.status === '部分入住',
                    'bg-red-100 text-red-800': viewData.status === '已满',
                    'bg-gray-100 text-gray-800': viewData.status === '维修中'
                  }"
                  class="inline-flex px-2 py-1 text-xs font-semibold rounded-full"
                >
                  {{ viewData.status }}
                </span>
              </div>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">宿舍设施</label>
              <div class="flex flex-wrap gap-2">
                <span
                  v-for="facility in viewData.facilities"
                  :key="facility"
                  class="inline-flex px-2 py-1 text-xs font-medium bg-blue-100 text-blue-800 rounded-full"
                >
                  {{ facility }}
                </span>
              </div>
            </div>
            <div v-if="viewData.remarks">
              <label class="block text-sm font-medium text-gray-700 mb-1">备注</label>
              <p class="text-sm text-gray-900">{{ viewData.remarks }}</p>
            </div>
          </div>
          
          <div class="flex justify-end pt-4">
            <button
              @click="showViewModal = false"
              class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors"
            >
              关闭
            </button>
          </div>
        </DialogPanel>
      </div>
    </Dialog>

    <!-- 住宿管理弹窗 -->
    <Dialog :open="showResidentModal" @close="showResidentModal = false" class="relative z-50">
      <div class="fixed inset-0 bg-black/30" aria-hidden="true" />
      <div class="fixed inset-0 flex items-center justify-center p-4">
        <DialogPanel class="w-full max-w-4xl rounded-lg bg-white p-6 shadow-xl">
          <DialogTitle class="text-lg font-medium text-gray-900 mb-4">
            住宿管理 - {{ currentDormitory?.roomNumber }}
          </DialogTitle>
          
          <div class="space-y-4">
            <!-- 床位布局 -->
            <div class="bg-gray-50 rounded-lg p-4">
              <h3 class="text-sm font-medium text-gray-700 mb-3">床位布局</h3>
              <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
                <div
                  v-for="bed in bedLayout"
                  :key="bed.number"
                  :class="{
                    'bg-green-100 border-green-300': !bed.occupied,
                    'bg-blue-100 border-blue-300': bed.occupied
                  }"
                  class="border-2 rounded-lg p-3 text-center cursor-pointer hover:shadow-md transition-all"
                  @click="handleBedClick(bed)"
                >
                  <div class="text-sm font-medium text-gray-700">床位 {{ bed.number }}</div>
                  <div class="text-xs text-gray-500 mt-1">
                    {{ bed.occupied ? bed.studentName : '空闲' }}
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 住宿学生列表 -->
            <div>
              <div class="flex items-center justify-between mb-3">
                <h3 class="text-sm font-medium text-gray-700">住宿学生</h3>
                <button
                  @click="showAssignBedModal = true"
                  class="px-3 py-1.5 text-sm font-medium text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors"
                >
                  分配床位
                </button>
              </div>
              <div class="border border-gray-200 rounded-lg overflow-hidden">
                <table class="min-w-full divide-y divide-gray-200">
                  <thead class="bg-gray-50">
                    <tr>
                      <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">学号</th>
                      <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">姓名</th>
                      <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">床位号</th>
                      <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">入住时间</th>
                      <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                    </tr>
                  </thead>
                  <tbody class="bg-white divide-y divide-gray-200">
                    <tr v-for="resident in currentResidents" :key="resident.id" class="hover:bg-gray-50">
                      <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ resident.studentId }}</td>
                      <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ resident.name }}</td>
                      <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ resident.bedNumber }}</td>
                      <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ resident.checkInDate }}</td>
                      <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                        <button
                          @click="handleCheckOut(resident)"
                          class="text-red-600 hover:text-red-900 transition-colors"
                        >
                          退宿
                        </button>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
          
          <div class="flex justify-end pt-4">
            <button
              @click="showResidentModal = false"
              class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors"
            >
              关闭
            </button>
          </div>
        </DialogPanel>
      </div>
    </Dialog>

    <!-- 分配床位弹窗 -->
    <Dialog :open="showAssignBedModal" @close="showAssignBedModal = false" class="relative z-50">
      <div class="fixed inset-0 bg-black/30" aria-hidden="true" />
      <div class="fixed inset-0 flex items-center justify-center p-4">
        <DialogPanel class="w-full max-w-2xl rounded-lg bg-white p-6 shadow-xl">
          <DialogTitle class="text-lg font-medium text-gray-900 mb-4">
            分配床位
          </DialogTitle>
          
          <div class="space-y-4">
            <input
              v-model="studentSearchForBed"
              type="text"
              placeholder="搜索未分配宿舍的学生"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
            />
            
            <div class="max-h-60 overflow-y-auto border border-gray-200 rounded-lg">
              <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                  <tr>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">学号</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">姓名</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">专业</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                  </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                  <tr v-for="student in filteredStudentsForBed" :key="student.id" class="hover:bg-gray-50">
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ student.studentId }}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ student.name }}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ student.major }}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                      <button
                        @click="handleAssignBed(student)"
                        class="text-blue-600 hover:text-blue-900 transition-colors"
                      >
                        分配
                      </button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
          
          <div class="flex justify-end pt-4">
            <button
              @click="showAssignBedModal = false"
              class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors"
            >
              关闭
            </button>
          </div>
        </DialogPanel>
      </div>
    </Dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useAppStore } from '../../stores/app'
import {
  Dialog,
  DialogPanel,
  DialogTitle,
  Listbox,
  ListboxButton,
  ListboxOptions,
  ListboxOption
} from '@headlessui/vue'
import {
  PlusIcon,
  MagnifyingGlassIcon,
  TrashIcon,
  ArrowDownTrayIcon,
  PencilIcon,
  EyeIcon,
  UsersIcon,
  UserPlusIcon,
  ChevronUpDownIcon,
  CheckIcon,
  BuildingOfficeIcon,
  HomeIcon,
  CheckCircleIcon
} from '@heroicons/vue/24/outline'

// 使用stores
const appStore = useAppStore()

// 响应式数据
const searchForm = ref({
  roomNumber: '',
  building: '',
  floor: '',
  type: '',
  status: ''
})

const showAddModal = ref(false)
const showEditModal = ref(false)
const showViewModal = ref(false)
const showBuildingModal = ref(false)
const showResidentModal = ref(false)
const showAssignBedModal = ref(false)
const loading = ref(false)
const selectedDormitories = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const studentSearchForBed = ref('')
const currentDormitory = ref(null)

const formData = ref({
  roomNumber: '',
  building: '',
  floor: '',
  type: '',
  totalBeds: 4,
  status: '空闲',
  facilities: [],
  remarks: ''
})

const buildingForm = ref({
  name: '',
  type: '男生宿舍',
  floors: 6,
  address: ''
})

const errors = ref({})
const viewData = ref(null)

// 模拟数据
const buildings = ref([
  {
    id: 1,
    name: '1号楼',
    type: '男生宿舍',
    floors: 6,
    address: '校园东区'
  },
  {
    id: 2,
    name: '2号楼',
    type: '女生宿舍',
    floors: 6,
    address: '校园西区'
  },
  {
    id: 3,
    name: '3号楼',
    type: '男生宿舍',
    floors: 8,
    address: '校园南区'
  }
])

const dormitories = ref([
  {
    id: 1,
    roomNumber: '101',
    building: '1号楼',
    floor: 1,
    type: '4人间',
    totalBeds: 4,
    occupiedBeds: 2,
    status: '部分入住',
    facilities: ['空调', '独卫', '阳台'],
    remarks: '朝南，采光良好'
  },
  {
    id: 2,
    roomNumber: '102',
    building: '1号楼',
    floor: 1,
    type: '4人间',
    totalBeds: 4,
    occupiedBeds: 4,
    status: '已满',
    facilities: ['空调', '独卫'],
    remarks: ''
  },
  {
    id: 3,
    roomNumber: '201',
    building: '2号楼',
    floor: 2,
    type: '6人间',
    totalBeds: 6,
    occupiedBeds: 0,
    status: '空闲',
    facilities: ['空调', '独卫', '阳台', '热水器'],
    remarks: '新装修'
  },
  {
    id: 4,
    roomNumber: '301',
    building: '3号楼',
    floor: 3,
    type: '4人间',
    totalBeds: 4,
    occupiedBeds: 0,
    status: '维修中',
    facilities: ['空调', '独卫'],
    remarks: '水管维修中'
  }
])

// 模拟学生数据
const students = ref([
  {
    id: 1,
    studentId: '2024001',
    name: '张三',
    major: '计算机科学与技术',
    dormitoryId: 1,
    bedNumber: 1,
    checkInDate: '2024-09-01'
  },
  {
    id: 2,
    studentId: '2024002',
    name: '李四',
    major: '计算机科学与技术',
    dormitoryId: 1,
    bedNumber: 2,
    checkInDate: '2024-09-01'
  },
  {
    id: 3,
    studentId: '2024003',
    name: '王五',
    major: '软件工程',
    dormitoryId: null,
    bedNumber: null,
    checkInDate: null
  },
  {
    id: 4,
    studentId: '2024004',
    name: '赵六',
    major: '电子信息工程',
    dormitoryId: null,
    bedNumber: null,
    checkInDate: null
  }
])

// 计算属性
const filteredDormitories = computed(() => {
  let result = dormitories.value
  
  if (searchForm.value.roomNumber) {
    result = result.filter(dormitory => 
      dormitory.roomNumber.toLowerCase().includes(searchForm.value.roomNumber.toLowerCase())
    )
  }
  
  if (searchForm.value.building) {
    result = result.filter(dormitory => dormitory.building === searchForm.value.building)
  }
  
  if (searchForm.value.floor) {
    result = result.filter(dormitory => dormitory.floor === parseInt(searchForm.value.floor))
  }
  
  if (searchForm.value.type) {
    result = result.filter(dormitory => dormitory.type === searchForm.value.type)
  }
  
  if (searchForm.value.status) {
    result = result.filter(dormitory => dormitory.status === searchForm.value.status)
  }
  
  return result
})

const totalPages = computed(() => {
  return Math.ceil(filteredDormitories.value.length / pageSize.value)
})

const paginatedDormitories = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredDormitories.value.slice(start, end)
})

const occupiedCount = computed(() => {
  return dormitories.value.reduce((sum, dormitory) => sum + dormitory.occupiedBeds, 0)
})

const availableBeds = computed(() => {
  return dormitories.value.reduce((sum, dormitory) => sum + (dormitory.totalBeds - dormitory.occupiedBeds), 0)
})

const currentResidents = computed(() => {
  if (!currentDormitory.value) return []
  return students.value.filter(student => student.dormitoryId === currentDormitory.value.id)
})

const bedLayout = computed(() => {
  if (!currentDormitory.value) return []
  const beds = []
  for (let i = 1; i <= currentDormitory.value.totalBeds; i++) {
    const resident = currentResidents.value.find(r => r.bedNumber === i)
    beds.push({
      number: i,
      occupied: !!resident,
      studentName: resident?.name || null
    })
  }
  return beds
})

const filteredStudentsForBed = computed(() => {
  let result = students.value.filter(student => !student.dormitoryId)
  if (studentSearchForBed.value) {
    result = result.filter(student => 
      student.name.includes(studentSearchForBed.value) ||
      student.studentId.includes(studentSearchForBed.value)
    )
  }
  return result
})

// 方法
const handleSearch = () => {
  currentPage.value = 1
}

const handleReset = () => {
  searchForm.value = {
    roomNumber: '',
    building: '',
    floor: '',
    type: '',
    status: ''
  }
  currentPage.value = 1
}

const handleSelectAll = (event) => {
  if (event.target.checked) {
    selectedDormitories.value = filteredDormitories.value.map(dormitory => dormitory.id)
  } else {
    selectedDormitories.value = []
  }
}

const handleEdit = (dormitory) => {
  formData.value = { ...dormitory }
  showEditModal.value = true
}

const handleView = (dormitory) => {
  viewData.value = dormitory
  showViewModal.value = true
}

const handleDelete = async (dormitory) => {
  if (confirm(`确定要删除宿舍 ${dormitory.roomNumber} 吗？`)) {
    const index = dormitories.value.findIndex(d => d.id === dormitory.id)
    if (index > -1) {
      dormitories.value.splice(index, 1)
      appStore.showNotification('删除成功', 'success')
    }
  }
}

const handleBatchDelete = async () => {
  if (selectedDormitories.value.length === 0) return
  
  if (confirm(`确定要删除选中的 ${selectedDormitories.value.length} 间宿舍吗？`)) {
    dormitories.value = dormitories.value.filter(dormitory => 
      !selectedDormitories.value.includes(dormitory.id)
    )
    selectedDormitories.value = []
    appStore.showNotification('批量删除成功', 'success')
  }
}

const handleBatchAssign = () => {
  if (selectedDormitories.value.length === 0) return
  appStore.showNotification('批量分配功能开发中', 'info')
}

const handleExport = () => {
  const csvContent = [
    ['宿舍号', '所属楼宇', '楼层', '类型', '总床位', '已入住', '状态', '设施', '备注'],
    ...filteredDormitories.value.map(dormitory => [
      dormitory.roomNumber,
      dormitory.building,
      dormitory.floor,
      dormitory.type,
      dormitory.totalBeds,
      dormitory.occupiedBeds,
      dormitory.status,
      dormitory.facilities.join('、'),
      dormitory.remarks || ''
    ])
  ].map(row => row.join(',')).join('\n')
  
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = `宿舍列表_${new Date().toISOString().split('T')[0]}.csv`
  link.click()
  
  appStore.showNotification('导出成功', 'success')
}

const handleManageResidents = (dormitory) => {
  currentDormitory.value = dormitory
  showResidentModal.value = true
}

const handleBedClick = (bed) => {
  if (bed.occupied) {
    appStore.showNotification(`床位 ${bed.number} 已被 ${bed.studentName} 占用`, 'info')
  } else {
    showAssignBedModal.value = true
  }
}

const handleAssignBed = async (student) => {
  // 找到第一个空闲床位
  const availableBed = bedLayout.value.find(bed => !bed.occupied)
  if (!availableBed) {
    appStore.showNotification('该宿舍已满', 'error')
    return
  }
  
  // 更新学生信息
  const studentIndex = students.value.findIndex(s => s.id === student.id)
  if (studentIndex > -1) {
    students.value[studentIndex] = {
      ...students.value[studentIndex],
      dormitoryId: currentDormitory.value.id,
      bedNumber: availableBed.number,
      checkInDate: new Date().toISOString().split('T')[0]
    }
  }
  
  // 更新宿舍入住数
  const dormitoryIndex = dormitories.value.findIndex(d => d.id === currentDormitory.value.id)
  if (dormitoryIndex > -1) {
    dormitories.value[dormitoryIndex].occupiedBeds++
    if (dormitories.value[dormitoryIndex].occupiedBeds === dormitories.value[dormitoryIndex].totalBeds) {
      dormitories.value[dormitoryIndex].status = '已满'
    } else {
      dormitories.value[dormitoryIndex].status = '部分入住'
    }
    currentDormitory.value = dormitories.value[dormitoryIndex]
  }
  
  showAssignBedModal.value = false
  appStore.showNotification(`成功为 ${student.name} 分配床位 ${availableBed.number}`, 'success')
}

const handleCheckOut = async (resident) => {
  if (confirm(`确定要为 ${resident.name} 办理退宿吗？`)) {
    // 更新学生信息
    const studentIndex = students.value.findIndex(s => s.id === resident.id)
    if (studentIndex > -1) {
      students.value[studentIndex] = {
        ...students.value[studentIndex],
        dormitoryId: null,
        bedNumber: null,
        checkInDate: null
      }
    }
    
    // 更新宿舍入住数
    const dormitoryIndex = dormitories.value.findIndex(d => d.id === currentDormitory.value.id)
    if (dormitoryIndex > -1) {
      dormitories.value[dormitoryIndex].occupiedBeds--
      if (dormitories.value[dormitoryIndex].occupiedBeds === 0) {
        dormitories.value[dormitoryIndex].status = '空闲'
      } else {
        dormitories.value[dormitoryIndex].status = '部分入住'
      }
      currentDormitory.value = dormitories.value[dormitoryIndex]
    }
    
    appStore.showNotification(`${resident.name} 退宿成功`, 'success')
  }
}

const validateForm = () => {
  errors.value = {}
  
  if (!formData.value.roomNumber) {
    errors.value.roomNumber = '请输入宿舍号'
  }
  
  if (!formData.value.building) {
    errors.value.building = '请选择所属楼宇'
  }
  
  return Object.keys(errors.value).length === 0
}

const handleSubmit = async () => {
  if (!validateForm()) return
  
  loading.value = true
  
  try {
    if (showAddModal.value) {
      const newDormitory = {
        id: Date.now(),
        ...formData.value,
        occupiedBeds: 0
      }
      dormitories.value.push(newDormitory)
      appStore.showNotification('添加成功', 'success')
    } else {
      const index = dormitories.value.findIndex(d => d.id === formData.value.id)
      if (index > -1) {
        dormitories.value[index] = { ...formData.value }
        appStore.showNotification('更新成功', 'success')
      }
    }
    
    closeModal()
  } catch (error) {
    appStore.showNotification('操作失败', 'error')
  } finally {
    loading.value = false
  }
}

const handleAddBuilding = async () => {
  const newBuilding = {
    id: Date.now(),
    ...buildingForm.value
  }
  buildings.value.push(newBuilding)
  buildingForm.value = {
    name: '',
    type: '男生宿舍',
    floors: 6,
    address: ''
  }
  showBuildingModal.value = false
  appStore.showNotification('楼宇添加成功', 'success')
}

const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  formData.value = {
    roomNumber: '',
    building: '',
    floor: '',
    type: '',
    totalBeds: 4,
    status: '空闲',
    facilities: [],
    remarks: ''
  }
  errors.value = {}
}

// 生命周期
onMounted(() => {
  // 初始化数据
})
</script>